from . import models
import time
from libs.ipay import alipay, alipay_gateway
from rest_framework.serializers import ModelSerializer,CharField,ValidationError
from django.conf import settings

class CreatePayLinkSerializers(ModelSerializer):
    good_pks = CharField(write_only=True)
    class Meta:
        model = models.Order
        fields = ['subject','total_amount','pay_type','good_pks']

        extra_kwargs = {
            'total_amount':{
                'required':True
            }
        }
    def validate(self, attrs):
        goods_pks = attrs.pop('good_pks')
        goods_list = goods_pks.split(',')
        goods_obj = []
        for course in goods_list:
            try:
                obj = models.Course.objects.get(pk=course)
                goods_obj.append(obj)
            except:
                raise ValidationError({'course':''})

        total_price = 0

        for obj in goods_obj:
            total_price += obj.price


        if total_price != attrs.get('total_amount'):
            raise ValidationError({'total_amount':'商品总价被恶意篡改'})


        #生成订单号
        order_on = int(round(time.time()*10000))

        #生成订单名字
        subject = attrs.get('subject')

        #生成订单链接
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_on,
            total_amount=float(attrs.get('total_amount')),
            subject=subject,
            return_url=settings.RETURN_URL,
            notify_url=settings.NOTIFY_URL
        )

        pay_url = alipay_gateway + order_string

        self.pay_url = pay_url

        attrs['out_trade_no'] = order_on

        attrs['user'] = self.context.get('request').user

        # print(self.context.get('request').user)
        attrs['courses'] = goods_obj

        return attrs


    def create(self, validated_data):
        courses = validated_data.pop('courses')
        #关系表操作
        order = super().create(validated_data)
        order_detail_list = []
        for course in courses:
            order_detail_list.append(models.OrderDetail(order=order,course=course,price=course.price,real_price=course.price))

        models.OrderDetail.objects.bulk_create(order_detail_list)
        return order



